﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.IO;

namespace SerialBrowserBridge.Devices
{
    public class SerialDevice: IBlockDevice
    {
        #region -- blockdevice --
		public void WriteBlock(string data)
        {
            if (port != null)
                port.Write(data);
        }

        public event Action<string> ReadBlock;

        public bool Initialize()
        {
            port = new SerialPort(String.Format("COM{0}", PortID), Baud);
            port.DataReceived += DataReceived;

            try
            {
                port.Open();
            }
            catch (Exception)
            {
                port.Dispose();
                port = null;
                return false;
            }

            return true;
        }

        public void DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (e.EventType == SerialData.Chars)
            {
                var bytesToRead = port.BytesToRead;
                var dataAsArray = new byte[bytesToRead];
                port.Read(dataAsArray, 0, bytesToRead);

                var dataAsString = Encoding.Default.GetString(dataAsArray);
                // Check for "form feed"
                if (dataAsString.LastIndexOf((char)12) != -1)
                {
                    data.Clear();

                    var index = dataAsString.LastIndexOf((char) 12);
                    data.Append(dataAsString.Substring(index + 1));
                } else {
                    data.Append(dataAsString);
                }

                if (ReadBlock != null)
                    ReadBlock(data.ToString());
            }
        }

        public event Action<string, bool> Error;
 
	    #endregion    
    
        private SerialPort port;
        private StringBuilder data = new StringBuilder();

        /// <summary>
        /// Id of port (e.g. COM1 => 1)
        /// </summary>
        public int PortID { get; set; }

        /// <summary>
        /// Baudrate
        /// </summary>
        public int Baud { get; set; }
        
    }
}
